﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;

namespace AzureVMDashboard.UI
{
    public class SettingsViewModel : ViewModelBase
    {
        public event EventHandler CloseRequested;

        public event UserInteraction NotifyUser; //used to display MEssage/MessageBox in UI
        public delegate bool UserInteraction(string message, bool canCancel); //ask to user or notify

        public SettingsViewModel() {
            //try
            //{
            //    IsAzurePowershellInstalled = App.Resources.VMController.CheckIfAzurePSIsInstalled();
            //}
            //catch
            //{
            //    IsAzurePowershellInstalled = false;
            //}
        }

        #region Properties
        //private bool _IsAzurePowerShellInstalled;
        //public bool IsAzurePowershellInstalled
        //{
        //    get { return _IsAzurePowerShellInstalled; }
        //    private set { _IsAzurePowerShellInstalled = value; }
        //}

        //public bool IsAzurePowershellNotInstalled
        //{
        //    get { return !_IsAzurePowerShellInstalled; }
        //}

        public String PublishSettingsFile
        {
            get { return Properties.Settings.Default.PublishSettingsFile; }
            set
            {
                if (value != Properties.Settings.Default.PublishSettingsFile)
                {
                    Properties.Settings.Default.PublishSettingsFile = value;
                    RaisePropertyChanged("PublishSettingsFile");
                }
            }
        }


        #endregion

        #region commands

        private RelayCommand _CmdSelectPublishSettings;
        public RelayCommand CmdSelectPublishSettings
        {
            get
            {
                if (_CmdSelectPublishSettings == null)
                {
                    _CmdSelectPublishSettings = new RelayCommand(() => DoCmdSelectPublishSettingsFile(), () => true);
                }
                return _CmdSelectPublishSettings;
            }
        }

        private RelayCommand _CmdDownloadPublishSettings;
        public RelayCommand CmdDownloadPublishSettings
        {
            get
            {
                if (_CmdDownloadPublishSettings == null)
                {
                    _CmdDownloadPublishSettings = new RelayCommand(() => DoCmdDownloadPublishSettings(), () => true);
                }
                return _CmdDownloadPublishSettings;
            }
        }

        private RelayCommand _CmdSave;
        public RelayCommand CmdSave
        {
            get
            {
                if (_CmdSave == null)
                {
                    _CmdSave = new RelayCommand(() => DoCmdSave(), () => true);
                }
                return _CmdSave;
            }
        }


        private RelayCommand _CmdCancel;
        public RelayCommand CmdCancel
        {
            get
            {
                if (_CmdCancel == null)
                {
                    _CmdCancel = new RelayCommand(() =>
                    {
                        //if (!IsAzurePowershellInstalled)
                        //    Application.Current.Shutdown(-1);

                        if (CloseRequested != null)
                            CloseRequested(this, null);
                    }, () => true);
                }
                return _CmdCancel;
            }
        }

        #endregion

        #region Do commands


        private void DoCmdSave()
        {
            bool wrongSettings = false;

            if (String.IsNullOrEmpty(Properties.Settings.Default.PublishSettingsFile))
                wrongSettings = true;

            if (!wrongSettings)
            {
                try
                {
                    var newSettingsFile = new FileInfo(Properties.Settings.Default.PublishSettingsFile);
                    if (App.Resources.VMController.PublishSettingsFile == null || 
                        newSettingsFile.FullName != App.Resources.VMController.PublishSettingsFile.FullName)
                    {
                        var initResult = App.Resources.VMController.InitializeController(newSettingsFile);
                        if (initResult)
                        {
                            if (App.Resources.VMController.AzureSubscriptions.Count > 0)
                            {
                                App.Resources.CurrentSubscription = App.Resources.VMController.AzureSubscriptions[0]; //always select the first
                                App.Resources.CurrentSubscription.RetrieveVMs();
                            }

                            Properties.Settings.Default.Save(); //settings are good
                            wrongSettings = false;
                        }
                        else
                        {
                            wrongSettings = true;
                        }
                    }

                }
                catch (Exception fe)
                {
                    Logger.LogEntry("Cannot save settings", fe);
                    wrongSettings = true;
                }
            }

            if (wrongSettings && NotifyUser != null)
                NotifyUser("The settings are wrong, The powershell commands cannot be executed properly. Check if the publishing settings file is correct", false);
            else
                CmdCancel.Execute(null);


        }

        private void DoCmdDownloadPublishSettings()
        {
            //the user needs to download the file generated by Azure (the file contains the management certificate)
            if (NotifyUser != null)
                NotifyUser("I'm going to download the publish settings file (.publishsettings) needed to manage the VMs. The file contains all the information required and a management certificate. Check your browser, authorize the download and copy the file in a secure location. Once downloaded you must set the path of the file in this settings page.", false);

            App.Resources.VMController.DownloadPublishSettings();
        }


        private void DoCmdSelectPublishSettingsFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.ValidateNames = true;
            ofd.DefaultExt = ".publishsettings";
            ofd.Filter = "Azure Publish Settings (*.publishsettings)|*.publishsettings";
            ofd.Multiselect = false;
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var result = ofd.ShowDialog();
            if (result.HasValue && result.Value)
            {
                PublishSettingsFile = ofd.FileName;
            }
        }

        #endregion
    }
}
